const formatTime = date => {
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minute = date.getMinutes()
  const second = date.getSeconds()

  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

const formatNumber = n => {
  n = n.toString()
  return n[1] ? n : '0' + n
}
//删除购物车
function deleteCart(id){
  wx.showModal({
    title: '删除购物车商品提示',
    content: '你确定要从购物车中删除该商品吗',
    success (res) {
      if (res.confirm) {
        var carts = wx.getStorageSync('carts')?  wx.getStorageSync('carts'): [];
        var newCart = [];
        if(carts) for(var index in carts){
          if(carts[index].id != id){
            newCart.push(carts[index]);
          }
        }
        console.log(newCart);
        wx.setStorageSync('carts', newCart);
        wx.showToast({
          title: '你已经成功删除了该商品',
        })
      } else if (res.cancel) {
        console.log('用户点击取消')
      }
    }
  })
}

//j将购物车商品添加到缓存
function addCart(product){
  console.log(product);
  //获取购物车信息
  var isHave = false;
  var carts = wx.getStorageSync('carts')?  wx.getStorageSync('carts'): [];
  if(carts) for(var index in carts){
    if(carts[index].id == product.id){
      isHave = true;
    }
  }
  if(!isHave){
    console.log(carts);
    carts.push(product)
    wx.setStorageSync('carts', carts)
  }else{
    wx.showToast({
      title: '购物车已经存在该商品，快去下单吧！',
      icon: 'none'
    })
    return;
  }
  //这里将购物车信息设置到缓存中
  wx.showToast({
    title: '添加成功',
  })
}

module.exports = {
  formatTime: formatTime,
  addCart: addCart,
  deleteCart: deleteCart
}
